//
//  pictureSelectorViewController.swift
//  Weibo
//
//  Created by 明丽 on 16/1/23.
//  Copyright © 2016年 明丽. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

private let selectorCellMargin: CGFloat = 5
private let rowCount: CGFloat = 3

private let maxImageCount = 9

class pictureSelectorViewController: UICollectionViewController {
     lazy var imageList = [UIImage]()
    
    init(){
        let w = (KWidth - (rowCount + 1) * selectorCellMargin) / rowCount
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: w, height: w)
        //设置间距
        layout.minimumInteritemSpacing = selectorCellMargin
        layout.minimumLineSpacing = selectorCellMargin
        //设置边距
        layout.sectionInset = UIEdgeInsetsMake(selectorCellMargin, selectorCellMargin, 0, selectorCellMargin)
        super.init(collectionViewLayout: layout)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override  func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView?.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
    
}
extension pictureSelectorViewController{
    //实现数据源方法
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = imageList.count == maxImageCount ? 0 : 1
        
        return imageList.count+delta
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        //        let red =  CGFloat(random() % 256) / 255.0
        //        let green = CGFloat(random() % 256) / 255.0
        //        let blue = CGFloat(random() % 256) / 255.0
        
        //        cell.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1)
        cell.selectorDelegate = self
        if indexPath.item == imageList.count{
            cell.image = nil
        }else{
            
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
}
//实现代理方法
extension pictureSelectorViewController : PictureSelectorCellDelegate{
    //实现代理方法
    
    func userWillSelectPicture(cell: PictureSelectorCell){
        if cell.image != nil {
            print("已经有图片了")
        return
        }
        //图片轮播器
        let picker = UIImagePickerController()
        //设置图片轮播器代理
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: PictureSelectorCell){
        
        
        if let indexPath = collectionView?.indexPathForCell(cell)
        {
            imageList.removeAtIndex(indexPath.item)
            collectionView?.reloadData()
            
        }
        
    }
}

//图片轮播器代理
extension pictureSelectorViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //获取图片保存到数组中
        imageList.append(image)
        //刷新页面
        collectionView?.reloadData()
        //我们需要手动给这个页面dismiss掉
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    
    
}

//申明协议
protocol PictureSelectorCellDelegate : NSObjectProtocol {
    //协议方法
    func userWillSelectPicture(cell: PictureSelectorCell)
    
    func userWillDeletePicture(cell: PictureSelectorCell)
    
}


//自定义cell
class PictureSelectorCell : UICollectionViewCell {
    //申明代理
    weak var selectorDelegate: PictureSelectorCellDelegate?
    //定义外部属性
    
    var image : UIImage? {
        didSet {
            addButton.setImage(image, forState: .Normal)
            deleteBtn.hidden = image == nil
        }
        
    }
    
    
    
    //实现监听方法
    @objc private func addBtnDidClick(){
        selectorDelegate?.userWillSelectPicture(self)
        print("我是图片")
        
        
    }
    @objc private func deleteBtnDidClick() {
        print("我是删除")
        selectorDelegate?.userWillDeletePicture(self)
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(deleteBtn)
        //设置约束
        addButton.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
            
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addButton.snp_top)
            make.right.equalTo(addButton.snp_right)
        }
        addButton.imageView?.contentMode = .ScaleAspectFill
        
        //添加监听事件
        addButton.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
        
    }
    
    //懒加在视图
    private lazy var addButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
    private lazy var deleteBtn = UIButton(imageName:"compose_photo_close", backImageName: nil )
    
}